import axios from 'axios'
import { message } from 'ant-design-vue'
import { saveAs } from 'file-saver';

// 创建 Axios 实例
const myAxios = axios.create({
  baseURL: 'http://47.97.186.40:8123',
  // baseURL: 'http://localhost:8123',
  timeout: 60000,
  withCredentials: true,
})

// 全局请求拦截器
myAxios.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    return config
  },
  function (error) {
    // Do something with request error
    return Promise.reject(error)
  },
)

// 全局响应拦截器`
myAxios.interceptors.response.use(
  function (response) {
    const { data } = response
    // 未登录
    if (data.code === 40100) {
      // 不是获取用户信息的请求，并且用户目前不是已经在用户登录页面，则跳转到登录页面
      if (
        !response.request.responseURL.includes('user/get/login') &&
        !window.location.pathname.includes('/user/login')
      ) {
        message.warning('请先登录')
        window.location.href = `/user/login?redirect=${window.location.href}`
      }
    }
    if (response.headers['content-type'] === 'image/png') {
      console.log(123)
      // 创建一个 Blob 对象
      const blob = new Blob([response.data], { type: response.headers['content-type'] });

      // 获取文件名（从响应头中获取或自定义）
      const filename = 'picture'

      // 使用 file-saver 保存文件
      saveAs(blob, filename);

      // 返回一个空对象或自定义对象，避免触发其他逻辑
      return Promise.resolve({});
    }
    return response
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error)
  },
)

export default myAxios
